package com.ccp.dev.qbdms.service;

import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.extend.model.ExtendSysFile;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.dao.WQbdQualitymanageDao;
import com.ccp.dev.qbdms.dao.WQbdQualitymanageSuDao;
import com.ccp.dev.qbdms.model.WQbdQualityRevSu;
import com.ccp.dev.qbdms.model.WQbdQualitymanage;
import com.ccp.dev.qbdms.model.WQbdQualitymanageSu;
import com.ccp.dev.qbdms.model.vo.Echarts;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.ReadAttachmentUtil;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysRole;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.system.util.SysRoleUtil;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.nio.protocol.NHttpRequestHandler;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;


/**
 * 质量管理体系 信息操作服务类
 *
 * @author 王明亮
 * @date 2020-05-12 10:39:53
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WQbdQualitymanageService extends BaseService<WQbdQualitymanage> {

    @Resource
    private SysOrgService sysOrgService;

    @Resource
    private WQbdQualitymanageDao dao;
    @Resource
    private WQbdQualitymanageSuDao wQbdQualitymanageSuDao;
    public HSSFWorkbook exportExcel(Excel excel, QueryFilter queryFilter) {
        List<WQbdQualitymanage> dataList = this.dao.queryAll(queryFilter);
        int startRow = 1;
        //给每一个单元格赋值
        for (WQbdQualitymanage data : dataList) {
            excel.cell(startRow, 0).value(data.getId());
            //excel.cell(startRow, 1).value(data.getMc());
            //可在赋值时，根据需求进行格式化
            //excel.cell(startRow, 2).value(DateFormatUtil.formatDate(data.getRq()));
            //excel.cell(startRow, 3).value(data.getSj());
            //excel.cell(startRow, 4).value(data.getTenantId());
            startRow++;
        }
        return excel.getWorkBook();
    }

    @Override
    public int delByIdArray(String[] ids) {
        wQbdQualitymanageSuDao.delByRefIds(ids);
        return super.delByIdArray(ids);
    }


    @Resource
    private ProcessRunService processRunService;

    @Override
    public int add( WQbdQualitymanage wQbdQualitymanage) {
        addSubData(wQbdQualitymanage);
        return super.add(wQbdQualitymanage);
    }
    public int update(WQbdQualitymanage wQbdQualitymanage, HttpServletRequest request) {
        SysRole currentRole = SysRoleUtil.getCurrentRole(request);
        String alias = currentRole.getAlias();
        if (alias.equals("bpm_zlzhzly")){
            wQbdQualitymanageSuDao.delByRefId(wQbdQualitymanage.getId());
            addSubData(wQbdQualitymanage);
        }else{
            List<WQbdQualitymanageSu> suList = wQbdQualitymanage
                .getwQbdQualitymanageSuList();
            if(!ObjectUtils.isEmpty(suList)){
                for (WQbdQualitymanageSu wQbdQualitymanageSu:suList){
                    wQbdQualitymanageSuDao.update(wQbdQualitymanageSu);
                }
            }
        }
        return super.update(wQbdQualitymanage);
    }
    private void addSubData(WQbdQualitymanage wQbdQualitymanage) {
        if (BeanUtils.isNotEmpty(wQbdQualitymanage.getwQbdQualitymanageSuList())) {
            if (wQbdQualitymanage.getwQbdQualitymanageSuList().size() > 0) {
                List<WQbdQualitymanageSu> wQbdQualitymanageSus = wQbdQualitymanage.getwQbdQualitymanageSuList();

                for (WQbdQualitymanageSu wQbdQualitymanageSu : wQbdQualitymanageSus) {
                    SysOrg org = sysOrgService.getSysOrgByOrgCode(wQbdQualitymanageSu.getResponsibleunit());
                    if (!ObjectUtils.isEmpty(org)){
                        wQbdQualitymanageSu.setResponsibleunitName(org.getOrgName());
                    }
                    wQbdQualitymanageSu.setId(ProjectUUIDUtils.getUUIDFor32());
                    wQbdQualitymanageSu.setRefid(wQbdQualitymanage.getId());
                    ZhiLiangConst.addCommonFields(wQbdQualitymanageSu);
                }
                wQbdQualitymanageSuDao.addList(wQbdQualitymanage.getwQbdQualitymanageSuList());
            }
        }
    }


    /**
     * 流程处理器方法 用于处理业务数据
     *
     * @param cmd
     */
    public void processHandler(ProcessCmd cmd) {
        Map data = cmd.getFormDataMap();
        if (BeanUtils.isNotEmpty(data)) {
            WQbdQualitymanage wQbdQualitymanage = JSONObject.parseObject(JSONObject.toJSONString(data), WQbdQualitymanage.class);
            if (StringUtil.isEmpty(cmd.getBusinessKey())) {
                String genId = UUIDUtils.getUUIDFor32();
                wQbdQualitymanage.setId(genId);
                wQbdQualitymanage.setCreateBy(ContextUtil.getCurrentUserId());
                wQbdQualitymanage.setCreateTime(new Date());
                wQbdQualitymanage.setTenantId(ContextUtil.getCurrentUserTenantId());
                wQbdQualitymanage.setTenantId(ContextUtil.getCurrentUserTenantId());
                this.add(wQbdQualitymanage);
            } else {
                wQbdQualitymanage.setId(cmd.getBusinessKey());
                wQbdQualitymanage.setUpdateBy(ContextUtil.getCurrentUserId());
                wQbdQualitymanage.setUpdateTime(new Date());
                this.update(wQbdQualitymanage);
            }
            cmd.setBusinessKey(wQbdQualitymanage.getId());
        }
    }

    /**
     * 重写getAll方法绑定流程runId
     */
    @Override
    public List<WQbdQualitymanage> queryList(QueryFilter queryFilter) {
        List<WQbdQualitymanage> wQbdQualitymanageList = super.queryList(queryFilter);
        List<WQbdQualitymanage> wQbdQualitymanages = new ArrayList<WQbdQualitymanage>();
        for (WQbdQualitymanage wQbdQualitymanage : wQbdQualitymanageList) {
            /*ProcessRun processRun = processRunService.getByBusinessKey(wQbdQualitymanage.getId());
            if (BeanUtils.isNotEmpty(processRun)) {
                wQbdQualitymanage.setRunId(processRun.getRunId());
            }*/
            wQbdQualitymanages.add(wQbdQualitymanage);
        }
        return wQbdQualitymanages;
    }

    /**
     * 院级用户内审流程修改上报状态
     *
     * @param cmd
     * @param agreeStatus
     * @param disAgreeStatus
     */
    public void updateStatus(ProcessCmd cmd, String agreeStatus, String disAgreeStatus) {
        String id = cmd.getBusinessKey();
        if (StringUtil.isNotEmpty(id)) {
            WQbdQualitymanage wQbdQualitymanage = super.getOneById(id);
            /*
             * 0=弃权,1=同意,2=反对,3=驳回, 4=追回, 5=会签通过, 6=会签不通过, 33=提交,34=再提交, 40=代提交
             */
            int vote = cmd.getVoteAgree();
            if (vote == 1) {
                wQbdQualitymanage.setReportStatus(agreeStatus);
            } else if (vote == 2) {
                wQbdQualitymanage.setReportStatus(disAgreeStatus);
            }
            super.update(wQbdQualitymanage);
        }
    }

    /**
     * 查询上报流程的业务数据
     *
     * @param dataId
     * @param tableName
     * @return
     */
    public List<WQbdQualitymanage> reportList(String dataId, String tableName) {
        return dao.reportList(dataId, tableName);
    }

    /**
     * 导出用查询
     *
     * @param queryFilter 查询参数
     * @return list
     */
    public List<WQbdQualitymanage> queryAll(QueryFilter queryFilter) {

        List<WQbdQualitymanage> list = dao.queryAll(queryFilter);
        return list;




    }



    /**
     * 导入新增
     *
     * @param list 数据集
     * @throws Exception 异常
     */
    public void addImportData(List<WQbdQualitymanage> list) {
        ZhiLiangConst.addCommonFields(list);
        //上报状态
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        list.forEach(a -> {
            String mainId = ProjectUUIDUtils.getUUIDFor32();
            a.setId(mainId);
            a.setfTrialunitname(a.getFilldept());
            a.setfTrialunitnameid(a.getFilldeptid());
            if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)) {
                a.setReportStatus(ZhiLiangConst.HOSPITAL_INTERNALAPPROVAL_THEAPPROVALISPENDING);
            } else if (BaseUtil.SystemLevel.PLANTLEVEL.equals(currentSystemLevel)) {
                a.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            }
        });
        if (!list.isEmpty()) {
            dao.addList(list);
        }
    }

    /**
     * 根据主表id查询主表加子表数据
     *
     * @param id 主表id
     * @return
     */
    public WQbdQualitymanage getParentAndChilden(String id) {
        return getOneById(id);
    }

    /**
     * 保存接口传输的数据
     *
     * @param wQbdQualitymanageList 主表model,有子表的包含子表数据
     * @return
     */
    public void saveAll(List<WQbdQualitymanage> wQbdQualitymanageList, List<ExtendSysFile> extendSysFileList) {
        ReadAttachmentUtil.getEntityData(wQbdQualitymanageList, extendSysFileList);
        wQbdQualitymanageList.forEach(wQbdQualitymanage -> wQbdQualitymanage.setBelongdeptname(StringUtil.isNotEmpty(wQbdQualitymanage.getFilldeptHospitalId()) ? BaseUtil.getCurrentTenOrgCodePath(wQbdQualitymanage.getFilldeptHospitalId()) : BaseUtil.getCurrentTenOrgCodePath(wQbdQualitymanage.getFilldeptid())));
        wQbdQualitymanageList.forEach(wQbdQualitymanage -> {
            if (BeanUtils.isEmpty(dao.getById(wQbdQualitymanage.getId()))) {
                dao.add(wQbdQualitymanage);
            } else {
                dao.update(wQbdQualitymanage);
            }
        });
    }

    public List<WQbdQualitymanage> queryListBySu(QueryFilter queryFilter) {
       return dao.queryListBySu(queryFilter);
    }


    /**
     * 按类型统计
     * @param queryFilter
     * @return
     */
    public Map<String,Object> fAudittypeSta(QueryFilter queryFilter){
        Map<String,Object> map=new HashMap<>();
        List<WQbdQualitymanage> list= dao.fAudittypeSta(queryFilter);
        List<String> set=new ArrayList<>();
        List<Echarts> echartsSet=new ArrayList<>();
        for (int i=0;i<list.size();i++){
           Echarts echarts=new Echarts();
           echarts.setValue(list.get(i).getCount());
           echarts.setName( list.get(i).getfAudittype());
           set.add(list.get(i).getfAudittype());
           echartsSet.add(echarts);
        }
         map.put("legend_data",set);
         map.put("series_data",echartsSet);
         map.put("date",queryFilter.get("fAudittime"));
         return map;
    }


    /**
     * 按不合格项性质统计
     * @param queryFilter
     * @return
     */
    public Map<String,Object> fUnqualifiednatureSta(QueryFilter queryFilter){
        Map<String,Object> map=new HashMap<>();
        List<WQbdQualitymanage> list= dao.fUnqualifiednatureSta(queryFilter);
        List<String> set=new ArrayList<>();
        List<Echarts> echartsSet=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            Echarts echarts=new Echarts();
            echarts.setValue(list.get(i).getCount());
            echarts.setName( list.get(i).getfUnqualifiednature());
            set.add(list.get(i).getfUnqualifiednature());
            echartsSet.add(echarts);
        }
        map.put("legend_data",set);
        map.put("series_data",echartsSet);
        map.put("date",queryFilter.get("fAudittime"));
        return map;
    }


    /**
     * 按 标准条款统计
     * @param queryFilter
     * @return
     */
    public Map<String,Object> fstandardclauseSta(QueryFilter queryFilter){
        Map<String,Object> map=new HashMap<>();
        List<WQbdQualitymanageSu> list = wQbdQualitymanageSuDao
            .fstandardclauseSta(queryFilter);
        List<String> set=new ArrayList<>();
        List<String> unitnameSet=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            unitnameSet.add(list.get(i).getFstandardclause());
            set.add(String.valueOf(list.get(i).getCount()));
        }
        map.put("legend_data",set);
        map.put("series_data",unitnameSet);
        map.put("date",queryFilter.get("fAudittime"));
        return map;
    }
    /**
     * 按  子标准条款
     * @param queryFilter
     * @return
     */
    public Map<String,Object> fstandardclauseSuSta(QueryFilter queryFilter){
        Map<String,Object> map=new HashMap<>();
        List<WQbdQualitymanageSu> list = wQbdQualitymanageSuDao.fstandardclauseSuSta(queryFilter);
        List<String> set=new ArrayList<>();
        List<String> unitnameSet=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            unitnameSet.add(list.get(i).getFsubstandardclauses());
            set.add(String.valueOf(list.get(i).getCount()));
        }
        map.put("legend_data",set);
        map.put("series_data",unitnameSet);
        map.put("date",queryFilter.get("fAudittime"));
        return map;
    }




    /**
     * 按 受审单位统计
     * @param queryFilter
     * @return
     */
    public Map<String,Object> fTrialunitnameSta(QueryFilter queryFilter){
        Map<String,Object> map=new HashMap<>();
        List<WQbdQualitymanageSu> list= wQbdQualitymanageSuDao.responsibleunitSta(queryFilter);
        List<String> set=new ArrayList<>();
        List<String> unitnameSet=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            unitnameSet.add(list.get(i).getResponsibleunitName());
            set.add(String.valueOf(list.get(i).getCount()));
        }
        map.put("legend_data",set);
        map.put("series_data",unitnameSet);
        map.put("date",queryFilter.get("fAudittime"));
        return map;
    }

    public int updateFlowStatus(String businessKey){
        return dao.updateFlowStatus(businessKey);
    }
}
